from flask import session, redirect, url_for, g, request
from functools import wraps
from utils import restful
from exit import db
from .models import User
import hashlib
import time


def validate_login():
    salt = 'nx24Tej@R4gWVCopJkjHWjBo@n58LdQ5'   # 盐
    server_access = '&OSpYVy#6g^Q7Fo#'     # 参数
    sign1 = request.headers.get("sign", None)   # 接收的参数
    ts = request.headers.get("ts", None)    # 时间戳
    access = request.headers.get("access", None)  # 加密参数
    if ts is None or len(ts) != 13 or access != server_access or sign1 is None:
        # print(access, ts, sign1)
        return False

    # server_ts = round(time.time() * 1000)
    # if int(server_ts) - int(ts) >= 30000:
    #     print('时间戳不合法', int(server_ts), int(ts))
    #     return False

    sign2 = hashlib.sha256((ts + server_access + salt).encode('utf-8')).hexdigest()
    # print('客户端提交的sign：', sign1)
    # print('服务器生成的sign：', sign2)
    if sign1 != sign2:
        return False
    return True


def login_required(func):   # 登录限制
    @wraps(func)
    def need(*args, **kwargs):
        # g.user = User.query.filter_by(phone='15555555555').first()
        # return func(*args, **kwargs)
        login_ = validate_login()
        if login_ is not True:
            return restful.auth_error(message='201')
        token = request.headers.get("token", None)
        if token is not None:
            # print(token, '这是请求的token')
            user = User.verify_auth_token(token)
            # print(user)
            if user:
                g.user = user
                return func(*args, **kwargs)
            else:
                # print('---------')
                return restful.auth_error(message='请重新登录')
        else:
            return restful.auth_error(message='请前往登录!')
    return need


def login_need(func):
    @wraps(func)
    def need(*args, **kwargs):
        login_ = validate_login()
        if login_ is True:
            return func(*args, **kwargs)
        else:
            return restful.auth_error(message='201')
    return need


def login_required_query(func):   # 登录限制只查询
    @wraps(func)
    def need(*args, **kwargs):
        # g.user = User.query.filter_by(phone='15555555555').first()
        # return func(*args, **kwargs)
        login_ = validate_login()
        if login_ is not True:
            return restful.auth_error(message='201')
        token = request.headers.get("token", None)
        if token is not None:
            # print(token, '这是请求的token')
            user = User.verify_auth_token_query(token)
            # print(user)
            if user:
                g.user = user
                return func(*args, **kwargs)
            else:
                # print('---------')
                return restful.auth_error(message='请重新登录')
        else:
            return restful.auth_error(message='请前往登录!')
    return need




